import React, {useState, useEffect, useRef} from 'react'

const LogOn = () => {
    const [logon, setLogon] = useState({
        username: '',
        passwd: ''
    })
    const [success, setSuccess] = useState(0)
    const [school, setSchool] = useState('')
    const usernames = useRef()                //通过ref获得文本框数据
    const password  = useRef()
    
    useEffect(() => {
        fetch('http://39.96.84.223:4567/verify/adminlogin', {
            method: 'POST',                      //请求方法
            body: JSON.stringify(logon),          //请求的数据
            headers:{
                'Content-Type':'application/json'    //请求头编码方式json
            }
        })
        .then(res => {
            setSuccess(res.ok)
            return res.json()
        })
        .then(res => {
            if ( res ) setSchool(res.userinfo.university)
        })
        .catch(error => console.log("error:",error)) 
    }, [logon])

    const signIn = () => {
        setLogon({
            username: usernames.current.value,
            passwd: password.current.value
        })
    }

    return (
        <div style={{height: '50px',marginLeft:'50px',marginTop:'30px'}}>
            <div>
                <input ref={usernames} 
                    type="text" 
                    placeholder="请输入账号"
                />
            </div>
            <div>
                <input ref={password}  
                    type="password" 
                    placeholder="请输入密码"
                />
            </div>
            <div>
                <button onClick={signIn}>登录</button>
            </div>
            <div>
                {success === true?
                    <><h1>登录成功</h1>学校是{school}</>
                    :
                    <>{success === true?'登录失败':''}</>
                }
            </div>
        </div>
    )
} 

export default LogOn